import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
// 引入进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { localCache } from '@/utils/cache'
import { TOKEN } from '@/global/constant'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main.vue'),
    children: [
      {
        path: '/main',
        redirect: '/dashboard'
      }
    ]
  },
  {
    path: '/:pathMatch(.*)',
    component: () => import('@/views/not-found/not-found.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to) => {
  // 1.开启进度条
  NProgress.start()
  // 2.路由跳转
  const token = localCache.getCache(TOKEN) ?? {}
  // 如果没登录不能到主页面
  if (!token.value && to.path !== '/login') return '/login'
  // 如果登录了就不能回到login页
  if (token.value && to.path === '/login') return '/main'
  // 后续操作: 如果到'/main'页面, 再重定向到main页面第一页
  // if (to.path === '/main') return '/dashboard'
})
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})

export default router
